import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Roles } from '../entity/roles.entity';
import { RolesDto } from '../dto/roles.dto';
import { Auth } from 'src/entity/auth.entity';

@Injectable()
export class RolesService {
  constructor(
    @InjectRepository(Roles)
    private readonly rolesRepository: Repository<Roles>,
    @InjectRepository(Auth)
    private readonly authRepository: Repository<Auth>,
  ) {}

  async addRole(roleDto: RolesDto): Promise<Roles> {
    const roles = new Roles();
    const params = { ...roles, ...roleDto };
    return this.rolesRepository.save(params);
  }

  async queryRoles(): Promise<Roles[]> {
    return this.rolesRepository.find();
  }

  async getRoleById(id: string): Promise<Roles> {
    return this.rolesRepository.findOneBy({ id: id });
  }

  async deleteUserById(id: string): Promise<void> {
    await this.rolesRepository.delete(id);
  }

  /** 为角色分配权限 */
  async assignAuthToRole(roleId: string, authIds: string[]) {
    const role = await this.rolesRepository.findOne({
      where: { id: roleId },
      relations: ['auth'],
    });
    const auth = await this.authRepository.find({ where: { id: In(authIds) } });
    if (role && auth && authIds.length) {
      role.auth = [...role.auth, ...auth];
      return this.rolesRepository.save(role);
    }
  }
}
